// check show result
var isShow = false;
var mCurrentScore = 0;
// message score array
var scoreMessage = [
	" 0 : Oh my god!",
	" 1 : Try one more",
	" 2 : Try one more",
	" 3 : Try one more",
	" 4 : Not Bad",
	" 5 : Not Bad",
	" 6 : It's OK!",
	" 7 : Good!",
	" 8 : Your 're Clever!",
	" 9 : Excellent!",
	" 10 : Wow, Congratulation!!! You 're my idol :v"
	];

// time to challenge minutes
var timeTotal;
var timeCount = 0;
var extraPoint = 300;
var countDownInterval;

function doAjax(url) {
	var container = $('#target');
	if (url.match('^http')) {
		$.getJSON(
				"http://query.yahooapis.com/v1/public/yql?"
						+ "q=select%20*%20from%20html%20where%20url%3D%22"
						+ encodeURIComponent(url)
						+ "%22&format=xml'&callback=?",
				function(data) {
					if (data.results[0]) {
						data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
						
						container.html(data);
						
						removeTrashTag();
						
						saveData();
						
						loadData();
						
					} else {
						var errormsg = 'Could not load the page, maybe Server is maintaining!\nPlease come back later!';
						Android.showDialog("Server error", errormsg);
					}
				});
	} else {
		$('#target').load(url);
	}
}
	
function saveData(){
	//var resultContent = $("#correct-answer-content").html();
	//console.log("result content > " + resultContent);
	
	var number = 1;
    $(".vn_result").each(function() {
    	
    	var vnText = $(this).text();
        //$(this).prepend( number + ". ") ;
        var tagEn = $(".correct-answer:nth-child(" + number +") span");
        var enText = tagEn.html();
        tagEn.prepend(number + ". ");
        // append English - VN answer
        $(".correct-answer:nth-child(" + number +")").append("</br><span class='spanvn'>" + vnText + "</span>");
        
        // get sound url
        var soundUrl = $(".item-exam:nth-child(" + number +") a").attr('href');
        
        // load suggest question
        var tagSuggest = $(".suggest:nth-child(" + number +") p");
        var suggestion = tagSuggest.html();
        tagSuggest.prepend("<img class='volume' src='images/audio_headset.png' onclick='playSound( " + number + ", \"" + soundUrl + "\");'>" + number + ". ") ;
        
        var sid = getParameterByName(soundUrl, 'sid');
        
        // insert data into DB
        Android.saveAnswer(sid, suggestion, enText, vnText, soundUrl);
        
        number += 1;
    });
    
    // remove main content
    $('#target').html("");
}

function loadData(){
	// TODO load local data
	var answerJsonArray = JSON.parse(Android.loadOldAnswer());
	// Android.log("HTML", " >>> answerJsonArray " + answerJsonArray);
	for (var i = 0; i < answerJsonArray.length; i++) {
		var answerItem = answerJsonArray[i];
		
		// load suggestion
		var stt = i + 1;
		var soundTag = "<img class='volume' src='images/audio_headset.png' onclick='playSound( this , \"" + answerItem.soundUrl + "\");'>";
		$("#suggest_question").append("<div class='suggest'>" + soundTag + "<p>" + stt + ". " + answerItem.suggestion + "</p></div>");
		$("#result").append("<div class=\"correct-answer\"><span>"+ stt + ". " + answerItem.en +"</span></br><span class='spanvn'>"+ answerItem.vn +"</span></div>");
		$("#btn_check_answer").show();
		
		// add input text
		addInputAnswer(answerItem.suggestion, i + 1);
	}
	
	// check challenge mode
	if(Android.isChallengeMode()){
		$("#btn_show_result").hide();
		
		// start timer count down
		timeTotal = Android.getTimeChallenge();
		// console.log("timeTotal " + timeTotal)
		
		// start timer
		countDownInterval = setInterval(function(){
			
			if(timeCount >= timeTotal){
				// check result
				checkResult();
			} else {
				if(extraPoint > 0){
					extraPoint = extraPoint - 1; 
				}
				timeCount = timeCount + 1;
				Android.updateTimeCounter(timeCount, (extraPoint > 0 ? "+" + extraPoint : extraPoint));
			}
			
		}, 1000);
	} else {
		$("#btn_show_result").show();
	}
	
	// check language
//	if(Android.getLanguage() == "en"){
//		$(".spanvn").hide();
//	}
}

function removeTrashTag() {
	// remove 
    $(".btn-cont").remove();
    $(".nums-exam").remove();
}

function playSound(imgTag, sound_url){
	//console.log("number "+ number + ", url " + sound_url);
	/*var mySound = soundManager.createSound({
	      id: number,
	      url: sound_url
	    });
	mySound.play();*/
	// play native android
	Android.playAudio(sound_url);
	
	// change background icon
	$(imgTag).attr("src","images/audio_headset_active.png");
	setTimeout(function(){
		$(imgTag).attr("src","images/audio_headset.png");
	}, 3000);
	
}

function getURLParameter(url, name) {
	  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}

function getParameterByName(url, name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(url);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function addInputAnswer(strSuggest, rowIndex){
	
    var pattern = /_+/g;
    var count = strSuggest.match(pattern).length;
    for (var i = 1; i <= count; i++) {
		$(".suggest:nth-child(" + rowIndex +")").append("<input type=\"text\" class=\"input_answer\">");
	}
	//<p><input id="aswer1_1" type="text" style="width:100%"><input id="aswer1_2" type="text" style="width:100%"></p>
}

function checkResult(){

	// send GA
	Android.sendEvent("Check Result");
	
	var pattern = /_+/;
	var index = 1;
	var score = 0;
	$(".suggest").each(function() {
	
        var suggestion = $(this).children("p").html();
		$(this).children("input").each(function() {
			suggestion = suggestion.replace(pattern, this.value.trim());
		});
		
		//console.log(suggestion);
		
		var correctAnswer = $(".correct-answer:nth-child(" + index +") span:nth-child(1)").html();
		//console.log(">>> index " + index + " _ " + correctAnswer);
		if(index <= 10){
			if(suggestion.toLowerCase() == correctAnswer.toLowerCase()){
				score = score + 1;
				$(this).children("p").css("color","blue");
			} else {
				$(this).children("p").css("color","red");
			}
		}
        
        index += 1;
	});
	
	// set current score
	mCurrentScore = score;
	
	// check challenge mode
	if(Android.isChallengeMode()){
		
		// hide button
		$("#btn_check_answer").hide();
		// clear interval
		clearInterval(countDownInterval);
				
		var correctBonus = score * 100;
		if(score == 0){
			correctBonus = 0;
			extraPoint = 0;
		}
		var total = correctBonus + extraPoint; // example:  point = (score * 100) +  180 - 25
		// show dialog
		Android.showScoreDialog(score, correctBonus + " points", timeCount + " seconds", extraPoint + " points", total + " points");
		
		// prevent cheat
		if(total <= 1300) { 
			// update leader board score
			Android.submitScore(total);
		}
	} else {
		// show dialog
		Android.showDialog("Score", "Your scores : " + scoreMessage[score]);
	}
}

function showResult(){
	// send GA
	Android.sendEvent($("#btn_show_result").html());
	
	if(isShow){
		$("#result").hide();
		$("#btn_show_result").html("Show Result")
		isShow = false;
	} else {
//		if(mCurrentScore < 3){
//			Android.showDialog("Notice", "You need to answer correctly at least 3 sentences before you can know the result! Let try one more time!");
//		} else {
			$("#result").show();
			$("#btn_show_result").html("Hide Result")
			isShow = true;
//		}
			
			
	}
	
//	$("#result").slideToggle("slow");
}
